<template>
  <Dialog v-model="dialogVisible2" title="编辑" width="600" max-height="100" destroy-on-close>
    <Form :schema="schema" @register="formRegister" />
    <template #footer>
      <BaseButton type="primary" @click="formSubmit" :loading="addLoading">提交</BaseButton>
      <BaseButton @click="dialogVisible2 = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { ref, reactive, defineProps, defineEmits, watch } from 'vue'
import { Form, FormSchema } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useForm } from '@/hooks/web/useForm'
import { ElMessage } from 'element-plus'
import { addPlStudyPlanApi, addPlStudyScheduleApi } from '@/api/studyPlan/video'

const { required } = useValidator()
const dialogVisible2 = ref(false)
const currRow = ref({})
const { formRegister, formMethods } = useForm()
const { getElFormExpose, getFormData, setValues } = formMethods
const emit = defineEmits(['onSearch'])
const isShowModel = (row) => {
  currRow.value = row
  console.log(row, 'row')
  dialogVisible2.value = true
}
const schema = reactive<FormSchema[]>([
  {
    field: 'startTime',
    label: '开始时间',
    component: 'TimeSelect',
    componentProps: {
      format: 'HH:mm:ss',
      step: '00:05',
      start: '06:00',
      end: '23:59'
    },
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'endTime',
    component: 'TimeSelect',
    label: '结束时间',
    componentProps: {
      format: 'HH:mm:ss',
      step: '00:05'
    },
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    }
  },
  {
    field: 'status',
    component: 'Select',
    label: '状态',
    formItemProps: {
      rules: [required()]
    },
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '禁用',
          value: 0
        },
        {
          label: '启用',
          value: 1
        }
      ]
    }
  }
])
const addLoading = ref(false)
const formSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  const valid = await elFormExpose?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    console.log(formData, 'iiii')
    addLoading.value = true
    formData.studyPlanId = currRow.value.id
    addPlStudyScheduleApi(formData)
      .then((res) => {
        if (res.code == '00000') {
          dialogVisible2.value = false
          ElMessage({ message: '保存成功！', type: 'success' })
          emit('onSearch', '子组件数据')
        }
      })
      .finally(() => {
        addLoading.value = false
      })
  }
}

defineExpose({ isShowModel })
</script>
